package com.niiwoo.civet.trade.service.local.databackflow.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class DataBackflowListeners implements ApplicationContextAware {

    private ApplicationContext ctx;

    private List<DataBackflowListener> listenerList = new ArrayList<>(0);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext.getParent() == null) {
            ctx = applicationContext;
        }
    }

    @PostConstruct
    public void init() {
        Optional.ofNullable(ctx.getBeansOfType(DataBackflowListener.class)).ifPresent(m -> listenerList.addAll(m.values()));
    }

    public void onNotify(Long flowExecuteId, String userId, Long projectId, int currentExecuteTimes) {
        final String method_name = "借款流程数据回流总监听器监听到回流需求, flowExecuteId:" + flowExecuteId + ", userId:" + userId + ", projectId:" + projectId;

        listenerList.stream()
                .filter(listener -> !listener.isBackflowSuccess(userId, projectId))
                .forEach(listener -> {
                    CompletableFuture.runAsync(() -> listener.handle(flowExecuteId, userId, projectId, currentExecuteTimes)).whenComplete((aVoid, throwable) -> {
                        if (throwable != null) {
                            log.error(method_name + "-通知各个回流监听器失败...", throwable);
                        } else {
                            log.info(method_name + "-通知各个回流监听器成功...");
                        }
                    });
                });

    }

}
